<template>
  <el-card class="box-card">
  <div slot="header" class="clearfix">
   <span v-if="isEdit">试题录入</span>
   <span v-else>试题编辑</span>
  </div>
  <el-form ref="form" :rules="rules" :model="form" label-width="60px" class="demo-form">
    <!-- 学科下拉框 -->
     <el-form-item label="学科" prop="subjectID" label-width="120px">
       <el-select @change="getChange" class='setSize' v-model="form.subjectID" placeholder="请选择">
         <el-option v-for="subject in mySubjects" :key="subject.value" :label="subject.label" :value="subject.value"></el-option>
       </el-select>
     </el-form-item>
     <el-form-item label="目录" prop="catalogID" label-width="120px">
       <el-select class='setSize' v-model="form.catalogID" placeholder="请选择">
         <el-option v-for="catalog in myCatalog" :key="catalog.value" :label="catalog.label" :value="catalog.value"></el-option>
       </el-select>
     </el-form-item>
     <el-form-item label="企业" prop="enterpriseID" label-width="120px">
       <el-select class='setSize' v-model="form.enterpriseID" placeholder="请选择企业">
         <el-option v-for="company in myCompany" :key="company.id" :label="company.company" :value="company.id"></el-option>
       </el-select>
     </el-form-item>
     <el-form-item label="城市" prop="province" label-width="120px">
       <el-select @change="getCitys" class='setSize' style="width:190px" v-model="form.province" placeholder="请选择城市">
         <el-option v-for="province in myProvinces" :key="province" :label="province" :value="province"></el-option>
       </el-select>
       <el-select class='setSize' style="width:190px; margin-left: 5px" v-model="form.city" placeholder="请选择地区">
         <el-option v-for="city in myCitys" :key="city" :label="city" value="city"></el-option>
       </el-select>
     </el-form-item>
     <el-form-item label="方向" prop="direction" label-width="120px">
       <el-select class='setSize' v-model="form.direction" placeholder="请选择">
         <el-option v-for="dir in myDirection" :key="dir" :label="dir" :value="dir"></el-option>
       </el-select>
     </el-form-item>
    <el-form-item label="题型" prop="questionType" label-width="120px">
      <el-radio-group v-model="form.questionType">
         <el-radio v-for="quest in myQuestionType" :key="quest.value" :value="quest.value" :label="quest.value">{{quest.label}}</el-radio>
       </el-radio-group>
    </el-form-item>
    <el-form-item label="难度" prop="difficulty" label-width="120px">
      <el-radio-group v-model="form.difficulty">
         <el-radio v-for="difficult in myDifficulty" :key="difficult.value" :value="difficult.value" :label="difficult.value">{{difficult.label}}</el-radio>
       </el-radio-group>
    </el-form-item>
    <el-form-item prop="question" label-width="120px" label="题干：">
       <quill-editor @blur="checkQuestion" v-model="form.question" :options="editorOption"></quill-editor>
    </el-form-item>
    <!-- 单选 -->
    <el-form-item label="单选" label-width="120px" v-if="this.form.questionType === 1">
        <div v-for="(item, index) in form.option" :key="index" style="margin-bottom:20px">
          <el-radio-group @change="chooseAnswer(item)" v-model="form.optionAns">
          <el-radio :label="item.code">
            <span>{{item.code}}： </span>
            <el-input
                style="width: 240px;"
                v-model="item.title"
                label="">
            </el-input>
          </el-radio>
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            style="display: inline-block;margin-left: 4px;position: relative;"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove">
            <el-button size="small" style="width: 100px;height: 60px; border: dashed 1px #999">点击上传</el-button>
          </el-upload>
          </el-radio-group>
        </div>
       <div>
         <el-button size="small" type="danger" disabled>+增加选项与答案</el-button>
       </div>
    </el-form-item>
    <!-- 多选 -->
    <el-form-item label="多选" label-width="120px" v-if="this.form.questionType === 2">
        <div v-for="(item, index) in form.options" :key="index" style="margin-bottom:20px">
          <el-checkbox-group
             style="display: inline-block;"
             v-model="form.optionsAns">
               <el-checkbox :label="item.code">
                 <span>{{item.code}}： </span>
               </el-checkbox>
          </el-checkbox-group>
          <el-input v-model="item.title"
             style="width: 240px;"
             label=""></el-input>
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
            style="display: inline-block;margin-left: 4px;position: relative;"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove">
            <el-button size="small" style="width: 100px;height: 60px; border: dashed 1px #999">点击上传</el-button>
          </el-upload>
        </div>
       <div>
         <el-button @click="addOption" size="small" type="danger">+增加选项与答案</el-button>
       </div>
    </el-form-item>
    <!-- 解析视频 -->
    <el-form-item label="解析视频:" label-width="120px" prop="videoURL">
          <el-input v-model="form.videoURL" class="setSize"></el-input>
    </el-form-item>
    <!-- 答案解析 -->
    <el-form-item prop="answer" label-width="120px" label="答案解析：">
       <quill-editor @blur="checkAnswer" v-model="form.answer" :options="editorOption"></quill-editor>
    </el-form-item>
    <!-- 题目备注 -->
    <el-form-item label="题目备注:" label-width="120px" prop="remarks">
       <el-input type="textarea"
       style="width: 400px;"
       v-model="form.remarks"
       rows="5"></el-input>
    </el-form-item>
    <!-- 试题标签下拉列表 -->
    <el-form-item prop="tags" label="试题标签" label-width="120px">
       <el-select multiple class='setSize' v-model="form.tags" placeholder="请选择">
         <el-option v-for="tag in myTag" :key="tag.value" :label="tag.label" :value="tag.value"></el-option>
       </el-select>
    </el-form-item>
    <el-form-item label-width="120px">
          <el-button type="primary"
          @click="onSubmit"
          v-if="isEdit"
          size="medium">确认提交</el-button>
          <el-button type="primary"
          @click="saveEdit"
          v-else
          size="medium">保存修改</el-button>
    </el-form-item>
  </el-form>
</el-card>

</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { simple } from '../../api/hmmm/subjects.js' // 学科
import { simple as dictionary } from '../../api/hmmm/directorys.js' // 目录
import { list } from '../../api/hmmm/companys.js' // 公司
import { provinces, citys } from '../../api/hmmm/citys.js' // 城市数据
import { direction, questionType, difficulty } from '../../api/hmmm/constants.js' // 方向
import { simple as tags } from '../../api/hmmm/tags'
import { add, detail, update } from '../../api/hmmm/questions.js' // 提交功能接口
export default {
  data () {
    // 验证城市
    var checkPovince = (rule, value, callback) => {
      if (this.form.province === '') {
        return callback(new Error('城市不能为空'))
      } else if (this.form.city === '') {
        return callback(new Error('地区不能为空'))
      } else {
        callback()
      }
    }
    return {
      isEdit: true, // 是否为编辑
      mySubjects: [], // 简单学科标题容器
      myCatalog: [], // 目录数据
      myCompany: [], // 公司数据
      myProvinces: [], // 城市数据
      myCitys: [], // 地区数据
      myDirection: [], // 方向数据
      myQuestionType: [], // 题型数据
      myDifficulty: [], // 试题难度
      myTag: [], // 试题标签
      // oneChoice: '', // 单选页面
      form: {
        name: '',
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        tags: '',
        question: '',
        videoURL: '',
        answer: '',
        remarks: '',
        optionAns: '', // 单选答案
        optionsAns: [], // 多选答案
        // 单选
        option: [
          {
            id: '',
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ],
        // 多选
        options: [
          {
            id: '',
            code: 'A',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'B',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'C',
            title: '',
            img: '',
            isRight: false
          },
          {
            id: '',
            code: 'D',
            title: '',
            img: '',
            isRight: false
          }
        ]
        // date1: '',
        // date2: '',
        // delivery: false,
        // type: [],
        // resource: '',
        // desc: ''
      },
      rules: {
        subjectID: [
          // 学科验证
          { required: true, message: '学科不能为空', trigger: 'change' }
        ],
        catalogID: [
          // 目录验证
          { required: true, message: '目录不能为空', trigger: 'change' }
        ],
        enterpriseID: [
          // 公司验证
          { required: true, message: '公司不能为空', trigger: 'change' }
        ],
        province: [
          // 城市地区验证
          { required: true, validator: checkPovince, trigger: 'change' }
        ],
        direction: [
          // 方向验证
          { required: true, message: '方向不能为空', trigger: 'change' }
        ],
        questionType: [
          // 题型验证
          { required: true, message: '题型不能为空', trigger: 'blur' }
        ],
        difficulty: [
          // 难度验证
          { required: true, message: '难度不能为空', trigger: 'blur' }
        ],
        question: [
          // 题干验证
          { required: true, message: '题干不能为空', trigger: 'blur' }
        ],
        // 视频地址
        // videoURL: [
        //   { required: true, message: '视频地址不能为空', trigger: 'blur' },
        //   { type: 'url', message: '视频地址格式错误', trigger: 'blur' }
        // ],
        // 答案解析
        answer: [
          { required: true, message: '答案解析不能为空', trigger: 'blur' }
        ]
      },
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      }
    }
  },
  watch: {
    // 使用监听器来处理路由数据得动态变化
    // 如果传过来的参数有id,说明是修改页面
    '$route.query.id': function (newVal, oldVal) {
      if (newVal) {
        this.isEdit = false
        this.getDetails(newVal)
      } else {
        this.isEdit = true
        // 下面清空表单
        this.oneAnswer = ''
        this.form = {
          subjectID: '',
          province: '',
          city: '',
          catalogID: '',
          enterpriseID: '',
          direction: '',
          questionType: 1,
          difficulty: 1,
          question: '',
          videoURL: '',
          answer: '',
          remarks: '',
          tags: [],
          // 多选
          options: [
            {
              id: '',
              code: 'A',
              title: '',
              img: '',
              isRight: false
            },
            {
              id: '',
              code: 'B',
              title: '',
              img: '',
              isRight: false
            },
            {
              id: '',
              code: 'C',
              title: '',
              img: '',
              isRight: false
            },
            {
              id: '',
              code: 'D',
              title: '',
              img: '',
              isRight: false
            }
          ]
        }
        this.form.option = this.form.options
      }
    }
  },
  components: {
    quillEditor
  },
  created () {
    if (this.$route.query.id) {
      this.isEdit = false
      this.getDetails(this.$route.query.id)
    }
    this.getSubjects()
    this.getCatalog()
    this.getCompany()
    this.myProvinces = provinces()
    this.myDirection = direction
    this.myQuestionType = questionType
    this.myDifficulty = difficulty
    this.getTag()
  },
  methods: {
    async getDetails (id) {
      // 通过id填数据
      try {
        const res = await detail({ id })
        console.log(res)
        // 获取得数据
        // this.form = list.data
        this.form.subjectID = res.data.subjectID
        this.form.catalogID = res.data.catalogID
        this.form.enterpriseID = res.data.enterpriseID
        this.form.direction = res.data.direction
        this.form.questionType = Number(res.data.questionType)
        this.form.difficulty = Number(res.data.difficulty)
        this.form.question = res.data.question
        this.form.videoURL = res.data.videoURL
        this.form.answer = res.data.answer
        this.form.remarks = res.data.remarks
        this.form.tags = res.data.tags
        this.form.province = res.data.province
        this.form.city = res.data.city
        // 转换标签格式 字符串变数组
        this.form.tags = res.data.tags.split(',')
        // 处理表单字段和接口文档所需一致
        this.form.questionType = +this.form.questionType
        this.form.difficulty = +this.form.difficulty
        // 手动获取地区和目录数据
        this.getCatalog()
        this.myCitys = citys(this.form.province)
        // 处理选项
        // this.options.forEach((value) => {
        //   value.isRight = Boolean(value.isRight)
        //   if (value.isRight) {
        //     this.oneAnswer = value.code
        //   }
        // })
        // 选项排序
        res.data.options.sort((a, b) => {
          return a.code.charCodeAt() - b.code.charCodeAt()
        })
        switch (this.form.questionType) {
          // 单选
          case 1: {
            const rightItem = res.data.options.find(item => item.isRight)
            this.form.option = res.data.options.map(item => {
              return {
                code: item.code,
                title: item.title,
                img: item.img,
                isRight: Boolean(item.isRight)
              }
            })
            this.form.optionAns = rightItem ? rightItem.code : ''
            break
          }
          // 多选
          case 2: {
            // 判断第0个的code是不是A 不是就reverse 不写选项就反了
            // if (this.form.options[0].code !== 'A') this.form.options.reverse()
            // this.form.options.forEach(value => {
            //   value.isRight = Boolean(value.isRight)
            // })
            this.form.options = res.data.options.sort((a, b) => {
              return a.code.charCodeAt() - b.code.charCodeAt()
            }).map(item => {
              return {
                code: item.code,
                title: item.title,
                img: item.img,
                isRight: Boolean(item.isRight)
              }
            })
            this.form.optionsAns = res.data.options.filter(item => item.isRight).map(item => item.code)
            break
          }
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 提交
    onSubmit () {
      this.$refs.form.validate(valid => {
        valid && this.sendMessage()
      })
    },
    // 保存修改
    saveEdit () {
      // 获取id值
      const id = this.$route.query.id
      this.$refs.form.validate(valid => {
        valid && this.saveData(id)
      })
    },
    // 发送提交请求
    async sendMessage () {
      // 把number类型改成str
      this.form.questionType += ''
      this.form.difficulty += ''
      this.form.tags = this.form.tags.toString()
      // 判断是单选还是多选,做进一步处理
      if (this.form.questionType === '1') {
        this.form.options = this.form.option
        this.form.options = this.form.option.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionAns === item.code
          }
        })
      } else if (this.form.questionType === '2') {
        this.form.options = this.form.options.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionsAns.includes(item.code)
          }
        })
      }
      try {
        const res = await add(this.form)
        if (res.status === 200) {
          this.$message.success('发布成功!1s后自动跳转')
          setTimeout(() => {
            this.$router.push('list')
          }, 1000)
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 发送修改请求
    async saveData (id) {
      id = +id
      this.form.id = id
      this.form.difficulty += ''
      this.form.questionType += ''
      this.form.tags = this.form.tags.toString()
      // 判断是单选还是多选,做进一步处理
      if (this.form.questionType === '1') {
        this.form.options = this.form.option
        this.form.options = this.form.option.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionAns === item.code
          }
        })
      } else if (this.form.questionType === '2') {
        this.form.options = this.form.options.map(item => {
          return {
            code: item.code,
            title: item.title,
            img: item.img,
            isRight: this.form.optionsAns.includes(item.code)
          }
        })
      }
      try {
        const res = await update(this.form)
        if (res.status === 200) {
          this.$message.success('修改成功!1s后自动跳转')
          setTimeout(() => {
            this.$router.push('list')
          }, 1000)
        }
      } catch (err) {
        console.log(err)
      }
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    beforeRemove (file, fileList) {
      return this.$confirm('确定移除？')
    },
    async getSubjects () {
      try {
        const { data: res } = await simple()
        console.log(res)
        this.mySubjects = res
      } catch (err) {
        console.log(err)
      }
    },
    async getCatalog () {
      if (!this.$route.query.id) {
        this.form.catalogID = ''
      }
      try {
        const res = await dictionary({ subjectID: this.form.subjectID })
        console.log(res)
        this.myCatalog = res.data
      } catch (err) {
        console.log(err)
      }
    },
    async getCompany () {
      try {
        const res = await list()
        console.log(res)
        this.myCompany = res.data.items
      } catch (err) {
        console.log(err)
      }
    },
    getCitys () {
      this.form.city = ''
      this.myCitys = []
      console.log(citys(this.form.province))
      this.myCitys = citys(this.form.province)
    },
    async getTag () {
      if (!this.$route.query.id) {
        this.form.tags = ''
      }
      try {
        const res = await tags({ subjectID: this.form.subjectID })
        console.log(res)
        this.myTag = res.data
      } catch (err) {
        console.log(err)
      }
    },
    getChange () {
      this.getCatalog()
      this.getTag()
    },
    // 设置单选答案
    chooseAnswer (item) {
      this.form.option.forEach(value => {
        value.isRight = false
        if (value.code === item.code) {
          value.isRight = true
        }
      })
    },
    // 添加选项
    addOption () {
      const data = {
        id: '',
        code: String.fromCharCode(this.form.options.length + 65),
        title: '',
        img: '',
        isRight: false
      }
      this.form.options.push(data)
    },
    // 校验题干
    checkQuestion () {
      this.$refs.form.validateField('question')
    },
    // 校验答案解析
    checkAnswer () {
      this.$refs.form.validateField('answer')
    }
  }
}
</script>

<style lang='css' >
  .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  /* // .box-card {
  //   width: 480px;
  // } */
  .setSize {
    width: 480px;
  }
  .ql-editor{
    min-height: 300px;
  }
  .publish-container .ql-toolbar.ql-snow{
    padding: 0 8px;
  }
</style>
